
"""扩展合作伙伴类别，增加对某些证照的限定功能"""

from odoo import models, api, fields
from odoo.tools import float_compare
from odoo.exceptions import UserError, ValidationError


class NecessaryLicense(models.Model):
    _name = 'gsp.necessary.license'
    _description = '合作伙伴需要提供的证照'

    supplier_categ_id = fields.Many2one('gsp.supplier.categ', string="供应商需要的添加的证照")
    customer_categ_id = fields.Many2one('gsp.customer.categ', string="客户需要的添加的证照")

    license_ids = fields.Many2many('gsp.license.template', string="所需证照")
    necessary_count = fields.Integer('至少提供')

    @api.constrains('license_ids', 'necessary_count')
    def constrain_necessary_count(self):
        """限制”提供数量“不能大于填写的”所需证照“数量"""
        for order in self:
            if order.necessary_count > len(order.license_ids):
                raise ValidationError(f'所需证照数量：{order.necessary_count}不能大于已添'
                                      f'加的”所需证照“的总数：{len(order.license_ids)}')


class SupplierCategory(models.Model):
    _inherit = 'gsp.supplier.categ'

    necessary_license_ids = fields.One2many('gsp.necessary.license', 'supplier_categ_id', string="需要的证照",
                                            readonly=True, states={'draft': [('readonly', False)]},)


class CustomerCategory(models.Model):
    _inherit = 'gsp.customer.categ'

    necessary_license_ids = fields.One2many('gsp.necessary.license', 'customer_categ_id', string="需要的证照",
                                            readonly=True, states={'draft': [('readonly', False)]},)

